﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace VirtualOperator
{
    public delegate void LogAppend(object sender, string lineMessage);
    public enum Task { CONNECT_TO_PICSNC,GET_ACCESIBLE_MATRIXES, NEW_VIRTUAL_NETWORK, NEW_VIRTUAL_LINK, ADD_SINK, ADD_SOURCE, SETUP_CONNECTION, TEARDOWN_CONNECTION, REMOVE_VIRTUAL_NETWORK, REMOVE_SINK, REMOVE_SOURCE, REMOVE_VIRTUAL_LINK, REMOVE_VIRTUAL_CONNECTION, DISCONNECT_PICSNC, VNO_UP, VNO_DOWN, UNKNOWN }
    public class LogMessages
    {
        private static LogMessages logMessages = null;
        private string logFileName;
        private StreamWriter w;
        public event LogAppend LogAppendHanlder = null;


        private LogMessages()
        {
            logFileName = "Log.txt";
            w = File.AppendText(logFileName);
        }

        public static LogMessages GetInstance()
        {
            if (logMessages == null)
                logMessages = new LogMessages();

            return logMessages;
        }

        public string ReadLog()
        {
            StreamReader r = File.OpenText(logFileName);
            return DumpLog(r);
        }


        public void AppendLog(Task task, string message)
        {
            DateTime time = DateTime.Now;
            string messageWithTime = String.Format("[{0}][{1}] {2}", time.TimeOfDay, task, message);
            w.WriteLine(messageWithTime);
            if (LogAppendHanlder != null)
            {
                LogAppendHanlder(this, messageWithTime);
            }
        }

        public void AppendLog(Task task, string vnoID, string message)
        {
            DateTime time = DateTime.Now;
            string messageWithTime = String.Format("[{0}][{1}][{2}] {3}", time.TimeOfDay, task, vnoID, message);
            w.WriteLine(messageWithTime);
            if (LogAppendHanlder != null)
            {
                LogAppendHanlder(this, messageWithTime);
            }
        }
        public void AppendLog(string message)
        {
            AppendLog(Task.UNKNOWN, message);
        }

        public void LogProtocol(int id, string message)
        {
            w.WriteLine(id + "#" + message);
        }


        private string DumpLog(StreamReader r)
        {
            // While not at the end of the file, read and write lines.
            string line;
            string logMessage = "";
            while ((line = r.ReadLine()) != null)
            {
                logMessage += line + Environment.NewLine;
            }
            r.Close();
            return logMessage;

        }
        public void Clean()
        {
            w.Close();
            LogAppendHanlder = null;
        }
    }
}
